/**
 * Copyright 2013-2017 JueYue (qrb.jueyue@gmail.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.thinkgem.jeesite.modules.gen.parse.impl;

import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.thinkgem.jeesite.modules.gen.GenConstants;
import com.thinkgem.jeesite.modules.gen.parse.IParse;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.StringTemplateResourceLoader;
import org.beetl.ext.spring.UtilsFunctionPackage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * 解析模板,生产代码
 *
 * @author JueYue
 * 2017年4月17日
 */
public class BeetlParseImpl implements IParse {
    private static final Logger LOGGER = LoggerFactory.getLogger(BeetlParseImpl.class);
    private static final StringTemplateResourceLoader RESOURCE_LOADER = new StringTemplateResourceLoader();

    private static Configuration CONFIGURATION;
    private static GroupTemplate GROUPTEMPLATE;

    static {
        try {
            // 使用默认配置，但是要忽略html标签
            CONFIGURATION = Configuration.defaultConfiguration();
            CONFIGURATION.setHtmlTagSupport(false);

            GROUPTEMPLATE = new GroupTemplate(RESOURCE_LOADER, CONFIGURATION);
            GROUPTEMPLATE.registerFunctionPackage("sputil", new UtilsFunctionPackage());
            GROUPTEMPLATE.registerFunctionPackage("sequenceUtil", new Sequence());
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    @Override
    public String parse(String templateContent, Map<String, ?> model) {
        Template t = GROUPTEMPLATE.getTemplate(templateContent);
        t.binding(GenConstants.BeetlParam.GLOBAL, model.get(GenConstants.ParseModel.GLOBAL));
        t.binding(GenConstants.BeetlParam.TABLE, model.get(GenConstants.ParseModel.TABLE));
        return t.render();
    }

}
